package com.hhc.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 示例中，我们定义了享元接口 Flyweight，然后实现了一个具体享元对象 CharacterFlyweight。
 * 享元工厂 FlyweightFactory 负责创建和管理享元对象，以确保字符对象可以被正确共享。
 * 客户端 TextEditor 使用享元工厂来获取并打印字符对象，同时维护字符的外部状态（位置）。
 */
// 享元接口
interface Flyweight {
    void print(String position);
}

// 具体享元对象
class CharacterFlyweight implements Flyweight {
    private char character;

    public CharacterFlyweight(char character) {
        this.character = character;
    }

    @Override
    public void print(String position) {
        System.out.println("Character " + character + " at position " + position);
    }
}

// 享元工厂
class FlyweightFactory {
    private Map<Character, Flyweight> flyweights = new HashMap<>();

    public Flyweight getCharacter(char character) {
        if (!flyweights.containsKey(character)) {
            flyweights.put(character, new CharacterFlyweight(character));
        }
        return flyweights.get(character);
    }
}

// 客户端
public class TextEditor {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();

        String text = "Hello, World!";
        char[] characters = text.toCharArray();

        for (int i = 0; i < characters.length; i++) {
            Flyweight flyweight = factory.getCharacter(characters[i]);
            flyweight.print(Integer.toString(i));
        }
    }
}